<template xmlns="">
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="入库单号" prop="formCode">
          <CodeRuleInput :band-value.sync="formData.formCode" table-name="wms_in_form" column-name="form_code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="入库人员" prop="name">
          <el-input v-model="formData.inByName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="入库时间" prop="purchaseTime">
          <el-date-picker
            v-model="formData.inTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="入库类型" prop="purchaseTypeCode">
          <el-input v-model="formData.formTypeName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="关联单据" class="clickChoose" prop="materialCode">
          <el-input v-model="formData.bindFormCode" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.fileUrl"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        入库明细
        <svg-icon icon-class="页面配置" @click.native="secondPageSetting" />
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="formData.details"
          max-height="400"
          stripe
          border
          style="width: 99.9%"
          :header-cell-class-name="headerCellClassName"
          @selection-change="selectionChange1"
        >
          <Column
            v-for="(column,index) in tableColumns"
            :key="index"
            :prop="column.prop"
            :is-show="column.isShow"
            :label="column.label"
            :sortable="column.sortable"
            :width="column.width"
            :min-width="column.minWidth"
            :fixed="column.fixed"
            :column-type="column.columnType"
            :is-tree="column.isTree"
          />
          <el-table-column label="入库仓库" min-width="150" prop="warehouseName" fixed="right">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.warehouseName"
                readonly
                placeholder="请选择"
                clearable
                @click.native="enterWarehouse(scope.row,scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column label="入库库位" min-width="150" prop="locationName" fixed="right">
            <template slot-scope="scope">
              <!--              <el-input-->
              <!--                v-model="scope.row.locationName"-->
              <!--                readonly-->
              <!--                placeholder="请选择"-->
              <!--                clearable-->
              <!--                @click.native="enterWarehouseLocation(scope.row,scope.$index)"-->
              <!--              />-->
              <el-select v-model="scope.row.locationId" :disabled="!scope.row.warehouseName" filterable clearable placeholder="请选择">
                <el-option
                  v-for="item in scope.row.locationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo } from '@/api/warehouseManagement/enterWarehouse'
import { list } from '@/api/warehouseManagement/storageModeling'
import moment from 'moment'
import warehouseLocation from '../storageModeling/warehouseLocation'
import warehouse from '../warehouseModeling/warehouse'
import { getSystemSet } from '@/api/common/systemSet'
import { mapGetters } from 'vuex'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      loading: false,
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        simpleName: undefined,
        categoryCode: undefined,
        belongBysStr: undefined,
        roleIdsArray: undefined,
        roleIds: undefined,
        typeId: undefined,
        model: undefined,
        purchaseTime: undefined,
        userId: undefined,
        protoId: undefined,
        protoName: undefined,
        typeName: undefined,
        realName: undefined,
        inTime: '',
        purchaseTypeCode: '',
        inBy: '',
        inByName: '',
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        remark: undefined,
        status: 1,
        details: []
      },
      warehouseId: '',
      locationId: '',
      tableHeight: '450',
      isShow: false,
      userOptions: [],
      equipmentList: [],
      selectionsAll1: [],
      ids: [],
      roleOptions: [],
      selectionsAll: [], // 表格所有页选中的行
      inx: 1,
      listDate: [],
      rules: {
        formCode: [
          { required: true, message: '申请单号不能为空', trigger: 'blur' }
        ]
      },
      tableColumns: [], // 表格实际用的字段
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'materialCode', label: '物料编码', minWidth: '140' },
        { prop: 'materialName', label: '物料名称', minWidth: '140' },
        { prop: 'materialModel', label: '规格型号', minWidth: '100' },
        { prop: 'materialTypeName', label: '物料分类' },
        { prop: 'materialUnitName', label: '物料单位' },
        { prop: 'descriptionName', label: '物料属性', isShow: false },
        { prop: 'materialWeight', label: '重量', isShow: false },
        { prop: 'materialTexture', label: '材质', isShow: false },
        { prop: 'materialBrand', label: '品牌', isShow: false },
        { prop: 'inStockNum', label: '入库数量', minWidth: this.SETTINGS.settings_decimalDigits_length },
        { prop: 'palletBatchCode', label: '批号', columnType: 'input', minWidth: '140' },
        { prop: 'productDate', label: '生产日期', columnType: 'time', minWidth: '140' },
        { prop: 'remark', label: '备注', columnType: 'input', minWidth: '240' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'companyId'
    ])
  },
  created() {
    this.getSecondPageSetting(this, '入库单新增或编辑', 'tableColumns', this.defaultTableColumns)
    if (!this.id) { // 没有id就是新增
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.formData.applicationName = this.$store.state.user.name
    this.formData.applicationBy = this.$store.state.user.userId
  },
  methods: {
    getSystemSet() {
      // 获取系统设置数据
      getSystemSet(this.companyId).then(res => {
        if (res.data.tacitlyApproveBatch == 1 && this.formData.formTypeName == '生产质检入库') {
          this.formData.details.filter((item) => {
            if (this.formData.formTypeName !== '生产质检入库') {
              item.palletBatchCode = ''
            }
          })
        }
      })
    },
    setFileName(...data) {
      this.$set(this.formData, 'fileName', data[0])
      this.$set(this.formData, 'fileRealName', data[1])
      this.$set(this.formData, 'fileUrl', data[2])
    },
    headerCellClassName(data) {
      if (['warehouseName', 'locationName'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData = res.data
        // this.formData.roleIdsArray = this.formData.roleIds.split(',')
        this.formData.details.filter((item, index) => {
          this.getLocationList({ warehouseId: item.warehouseId, rowIndex: index })
          // if (this.formData.formTypeName == '生产质检入库') {
          //   item.palletBatchCode = this.formData.bindFormCode
          // }
        })
        this.$nextTick(() => {
          this.formData.inBy = this.$store.state.user.userId
          this.formData.inByName = this.$store.state.user.userName
          this.formData.inTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          this.getSystemSet()
        })
      })
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.formData.details.splice(this.formData.details.indexOf(item), 1)
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.formData.details.filter(item => item.productDate > this.formData.inTime).length > 0) {
            this.$message.warning('生产日期不能晚于入库时间')
            return
          }
          if (this.formData.details.filter(item => !item.warehouseName).length > 0) {
            this.$message.warning('入库仓库不能为空')
            return
          }
          if (this.formData.details.filter(item => !item.locationId).length > 0) {
            this.$message.warning('入库库位不能为空')
            return
          }
          // this.formData.roleIds = this.formData.roleIdsArray
          addOrUpdate({ ...this.formData, status: '1' }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    // 选择仓库
    enterWarehouse(row, index) {
      this.rowIndex = index
      this.$layer.iframe({// 弹框
        content: {
          content: warehouse, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            warehouseId: row.warehouseId ? row.warehouseId : '',
            sparePartId: row.id
          }// props
        },
        area: ['880px', '570px'],
        title: '选择仓库', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择库位
    // enterWarehouseLocation(row, index) {
    //   const detailsOne = this.$deepClone(this.formData.details)
    //   detailsOne.forEach(item => {
    //     if (row.warehouseId == item.warehouseId) {
    //       this.warehouseId = row.warehouseId
    //     }
    //   })
    //   if (this.isShow) {
    //     this.rowIndex = index
    //     this.$layer.iframe({// 弹框
    //       content: {
    //         content: warehouseLocation, // 传递的组件对象
    //         parent: this, // 当前的vue对象
    //         data: {
    //           sparePartId: this.warehouseId ? this.warehouseId : '',
    //           templateSelection: row.locationId ? row.locationId : ''
    //         }// props
    //       },
    //       area: ['880px', '570px'],
    //       title: '选择库位', // 标题
    //       shadeClose: false // 点击遮罩是否关闭
    //     })
    //   } else {
    //     this.$message.warning('请先选择仓库')
    //     return
    //   }
    // },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    showMaterial(data) {
      data.forEach(item => {
        item.materialId = item.id
        item.id = ''
        item.remark = ''
        delete item.id
      })
      this.formData.details = data
    },
    // // 选择库位回调
    // showWarehouseLocation(row, checked) {
    //   const arr = this.$deepClone(this.formData.details)
    //   arr[this.rowIndex].locationId = row.id
    //   arr[this.rowIndex].locationName = row.locationName
    //   this.locationId = row.id
    //   this.formData.details = arr
    // },
    // 选择仓库回调
    showWarehouse(row, checked) {
      if (checked == false) { // 没有默认其他物料也加入该仓库
        const arr = this.$deepClone(this.formData.details)
        arr[this.rowIndex].warehouseId = row.id
        arr[this.rowIndex].warehouseName = row.name
        arr[this.rowIndex].locationName = row.locationName
        arr[this.rowIndex].locationId = row.locationId
        arr.details = row.details
        this.warehouseId = row.id
        this.$set(arr, 'warehouseName', row.name)
        this.formData.details = arr
        this.isShow = true
      } else { // 默认其他物料也加入该仓库
        const arr = this.$deepClone(this.formData.details)
        arr.forEach((item, index) => {
          item.warehouseId = row.id
          item.warehouseName = row.name
          item.locationName = row.locationName
          item.locationId = row.locationId
          this.warehouseId = row.id
          item.details = row.details
        })
        this.formData.details = arr
        this.isShow = true
      }
      this.getLocationList({ warehouseId: this.warehouseId, rowIndex: this.rowIndex, checked: checked })
    },
    secondPageSetting() { // 二级页面，页面配置
      this.setSecondPageSetting('入库单新增或编辑', this.defaultTableColumns)
    },
    getLocationList(row) { // 仓库回调触发的方法，用来根据仓库id获取库位
      list({ pageNum: 1, pageSize: 9999, status: 1, warehouseId: row.warehouseId }).then(res => {
        if (row.checked == false) {
          const arr = this.$deepClone(this.formData.details)
          arr[row.rowIndex].locationOptions = []
          res.data.filter(item => {
            if (arr[row.rowIndex].warehouseId == item.warehouseId) {
              if (res.data.length == 1) {
                arr[row.rowIndex].locationName = item.locationName
                arr[row.rowIndex].locationId = item.id
              }
              arr[row.rowIndex].locationOptions.push({
                value: item.id,
                label: item.locationName
              })
            }
          })
          this.formData.details = arr
        } else {
          const arr = this.$deepClone(this.formData.details)
          arr.filter(item => {
            item.locationOptions = []
            res.data.filter(ele => {
              if (item.warehouseId == ele.warehouseId) {
                if (res.data.length == 1) {
                  item.locationName = ele.locationName
                  item.locationId = ele.id
                }
                item.locationOptions.push({
                  value: ele.id,
                  label: ele.locationName
                })
              }
            })
          })
          this.formData.details = arr
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.formItem_header{
  justify-content: flex-start !important;
  svg{
    margin-left: 10px;
    font-size: 14px;
    color: #387bfc;
    cursor: pointer;
  }
}
</style>
